package com.sun.future;

import java.util.concurrent.*;

public class ThenApplyExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        System.out.println("主线程开始");

        // 创建异步任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("初始任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "Hello";
        },executorService);

        // thenApply: 对结果进行转换（同步执行，在前一个任务的线程中执行）
        CompletableFuture<String> transformedFuture = future.thenApply(result -> {
            System.out.println("thenApply执行线程: " + Thread.currentThread().getName());
            return result + " World";
        });

        // thenApplyAsync: 对结果进行转换（异步执行，可能在新线程中执行）
        CompletableFuture<String> asyncTransformedFuture = transformedFuture.thenApplyAsync(result -> {
            System.out.println("thenApplyAsync执行线程: " + Thread.currentThread().getName());
            return result.toUpperCase();
        },executorService);

        System.out.println("最终结果: " + asyncTransformedFuture.get());
        System.out.println("主线程结束");

        executorService.shutdown();
    }
}
